package com.xu.tao.demos.base;

import com.mysql.jdbc.Driver;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

public class SourceCodeTest {

    public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
        Configuration configuration = new Configuration();
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setURL("jdbc:mysql://localhost:3306/spsm?useUnicode=true&amp;characterEncoding=utf8");
        dataSource.setPassword("root");
        dataSource.setUser("root");
        //设置environment
        Environment environment =  new Environment.Builder("dev").dataSource(dataSource).transactionFactory(new JdbcTransactionFactory()).build();
        configuration.setEnvironment(environment);
        //设置MapperRegistry
        //configuration.addMappers("com.xu.tao.demos.base");

        String resource = "com/xu/tao/demos/StudentMapper.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
        mapperParser.parse();


        DefaultSqlSessionFactory sqlSessionFactory = new DefaultSqlSessionFactory(configuration);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student student = new Student();
        student.setAge(14);
        student.setName("XiaoYi");
        mapper.insert(student);
        sqlSession.commit();
        System.out.println("OK");
        //设置
    }
}
